package net.sudot.commons.security;

import net.sudot.commons.json.JsonUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登陆用户拦截器
 *
 * @author tangjialin on 2017-06-14 0014.
 */
public class LoginUserHandlerInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /** 用户接口 */
    private AuthenticationProvider authenticationProvider;
    /** 用户类型 */
    private Class<?> userClass;

    public LoginUserHandlerInterceptor() {
    }

    public LoginUserHandlerInterceptor(Class<?> userClass, AuthenticationProvider authenticationProvider) {
        this.userClass = userClass;
        this.authenticationProvider = authenticationProvider;
    }

    /**
     * 请求前处理
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param handler  处理器
     * @return 是否继续执行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        try {
            Object principal = subject.getPrincipal();
            if (principal != null && userClass.isAssignableFrom(principal.getClass())) {
                Object loginUser = authenticationProvider.getUser(principal);
                if (loginUser == null) { throw new UnknownAccountException("用户不存在:" + JsonUtils.toJson(principal)); }
                request.setAttribute(LoginUser.class.getSimpleName(), loginUser);
            }
        } catch (Exception e) {
            logger.error("登录用户获取异常", e);
            subject.logout();
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 请求后处理
     *
     * @param request      HttpServletRequest
     * @param response     HttpServletResponse
     * @param handler      处理器
     * @param modelAndView 数据视图
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 获取用户接口
     *
     * @return 用户接口
     */
    public AuthenticationProvider getAuthenticationProvider() {
        return authenticationProvider;
    }

    /**
     * 设置用户接口
     *
     * @param authenticationProvider 用户接口
     */
    public LoginUserHandlerInterceptor setAuthenticationProvider(AuthenticationProvider authenticationProvider) {
        this.authenticationProvider = authenticationProvider;
        return this;
    }

    /**
     * 获取用户类型
     *
     * @return 用户类型
     */
    public Class<?> getUserClass() {
        return userClass;
    }

    /**
     * 设置用户类型
     *
     * @param userClass 用户类型
     */
    public LoginUserHandlerInterceptor setUserClass(Class<?> userClass) {
        this.userClass = userClass;
        return this;
    }
}